package com.miplus.ccrm.core.service.commission;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.miplus.ccrm.common.CmdResVo;
import com.miplus.ccrm.common.JPubUtils;
import com.miplus.ccrm.core.controller.vo.commission.CaseStatisticsReqVo;
import com.miplus.ccrm.core.controller.vo.commission.CaseStatisticsResVo;
import com.miplus.ccrm.core.controller.vo.commission.DeptRepayListReqVo;
import com.miplus.ccrm.core.controller.vo.commission.DeptReportResVo;
import com.miplus.ccrm.core.pojo.FiDeptRepaymentReport;
import com.miplus.ccrm.core.mapper.FiDeptRepaymentReportMapper;
import com.miplus.ccrm.core.service.ExportService;
import com.miplus.ccrm.core.service.crd.FiImportHistService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
* @author wangzl
* @description 针对表【fi_dept_repayment_report】的数据库操作Service实现
* @createDate 2025-03-11 17:38:51
*/
@Service
@Slf4j
public class FiDeptRepaymentReportServiceImpl extends MPJBaseServiceImpl<FiDeptRepaymentReportMapper, FiDeptRepaymentReport>
    implements FiDeptRepaymentReportService{

    @Resource
    private ExportService exportService;
    @Resource
    private FiImportHistService fiImportHistService;

    @Override
    public IPage<DeptReportResVo> getDeptRepayReport(DeptRepayListReqVo para)
    {
        return selectJoinListPage( new Page<>(para.getPageNum(),para.getPageSize()),
                DeptReportResVo.class,
                new MPJLambdaWrapper<FiDeptRepaymentReport>()
                        .selectAll(FiDeptRepaymentReport.class)
                        .in(para.getDept()!=null, FiDeptRepaymentReport::getSendtodept,para.getDept())
                        .in(para.getDisttag()!=null,FiDeptRepaymentReport::getDisttag,para.getDisttag())
                        .ge(StringUtils.isNotEmpty(para.getStartDate()),FiDeptRepaymentReport::getStatisticsDate,para.getStartDate())
                        .le(StringUtils.isNotEmpty(para.getEndDate()),FiDeptRepaymentReport::getStatisticsDate,para.getEndDate())
                        .eq(ObjectUtils.isNotNull(para.getBillStatus()),FiDeptRepaymentReport::getBillStatus,para.getBillStatus())
                        .eq(ObjectUtils.isNotNull(para.getBillMonth()),FiDeptRepaymentReport::getBillMonth,para.getBillMonth())
                        .selectAs("(select grpname from sys_grp where grpid = t.sendtodept)", DeptReportResVo::getSendtodeptname)
                        .selectAs("fun_getnames('SORTING.QUEUE',t.disttag)",DeptReportResVo::getDisttagdesc)
                        .selectAs("case when t.bill_status = 1 then '已结账' else '未结账' end",DeptReportResVo::getBillStatusDesc)

        );
    }
    @Override
    public CmdResVo refreshReport(String usrid, String billMonth)
    {
        try{
            String refreshMonth = billMonth;
            if(StringUtils.isEmpty(billMonth)){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                refreshMonth = sdf.format( new Date());
            }

            //获取当月最新的更新时间。
            FiDeptRepaymentReport fiDeptRepaymentReport = baseMapper.selectOne(
                    new LambdaQueryWrapper<FiDeptRepaymentReport>()
                            .eq(FiDeptRepaymentReport::getBillMonth,refreshMonth)
                            .orderByDesc(FiDeptRepaymentReport::getStatisticsDate)
                            .last("limit 1"));
            if( fiDeptRepaymentReport == null )
            {
                return new CmdResVo(-1,"没有找到需要刷新的记录");
            }
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
            String statisticsDate = sdf2.format(fiDeptRepaymentReport.getStatisticsDate());
            log.info("Start Refresh FiDeptRepaymentReport month:{}, statisticsdate:{}", refreshMonth, statisticsDate);
            Long ret = baseMapper.refresh(usrid, fiDeptRepaymentReport.getBillMonth(),statisticsDate);
            log.info("Update FiDeptRepaymentReport repay ratio ok:" + ret);
            List<FiDeptRepaymentReport> fiDeptRepaymentReportList = baseMapper.selectList(
                            new MPJLambdaWrapper<FiDeptRepaymentReport>()
                                    .eq("statistics_date",statisticsDate)
                                    .orderByDesc("ifnull(repay_ratio,0)")
                    );
            int pos = 0;
            BigDecimal lastRapayRatio = BigDecimal.valueOf(-1);
            for(FiDeptRepaymentReport x :  fiDeptRepaymentReportList)
            {
                if( ObjectUtils.isNull(x.getRepayRatio()))
                    x.setRepayRatio(BigDecimal.ZERO);
                if( x.getRepayRatio().compareTo(lastRapayRatio) != 0 ) {
                    pos++;
                    lastRapayRatio = x.getRepayRatio();
                }
                log.info("calDeptDayRepayment dept:{}, disttag:{}. targetKPI:{}, repayRatio:{}, kpivalue:{}, Pos={}",
                        x.getSendtodept(),x.getDisttag(),x.getKpitarget(),x.getRepayRatio(),x.getKpivalue(),pos);
                baseMapper.updateKpiRatio(x.getReportId(), pos, statisticsDate, x.getDisttag());
            }
            log.info("DeptDayRepayment refresh finished.");
            return new CmdResVo(0, "更新完成");
        } catch(Exception e){
            log.error(" FiDeptRepaymentReport refreshReport exception: " + e );
            return new CmdResVo(-1,"Exception :" +e);
        }
    }
    @Override
    public CmdResVo saveAsExcel(String usrid, DeptRepayListReqVo paras, HttpServletResponse response) {

        int pagesize = paras.getPageSize();
        if (pagesize > JPubUtils.exportMaxCount) {
            paras.setPageSize(JPubUtils.exportMaxCount);
        }

        IPage<DeptReportResVo> pages=getDeptRepayReport(paras);
        ArrayList arr=new ArrayList();

        String exptempid=JPubUtils.getExpTempID(paras.getExpfilename(),"机构回收统计表");
        String filename=JPubUtils.getExpFileName(
                paras.getExpfilename(),exptempid
        );

        pages.convert(u->{
            HashMap map=JPubUtils.toExportMap(u);
            if(map!=null) arr.add(map);
            return u;
        });
        CmdResVo resVo=exportService.ToExcel(
                response,
                arr,
                paras.getExpidlist(),
                paras.getExpnamelist(),
                filename,
                usrid
        );

        int okcount=resVo.getCount();
        if(okcount>0){
            fiImportHistService.AddExportHist(
                    resVo.getKeyId(),
                    usrid,
                    exptempid,
                    filename,
                    okcount
            );
        }

        return resVo;
    }
}




